<template>
  <div class="app-container">
    <!-- 表格状态切换按钮 -->
    <ul class="nav">
      <li v-for="v in navData" :class="{ active: v.value == queryParams.orderStatus }" @click="navChangeHandle(v.value)">
        {{ v.label }}
      </li>
    </ul>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <searchType v-for="v in searchProps" :data="v" :selects="sel_option[v.prop]" v-model="queryParams[v.prop]"
        :handleQuery="handleQuery">
      </searchType>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['gwc:record:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['gwc:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gwc:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['gwc:record:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录id" align="center" prop="recordId" />
      <el-table-column label="所属作业公司" align="center" prop="companyName"></el-table-column>
      <el-table-column label="驾驶员id" align="center" prop="driverId"></el-table-column>
      <el-table-column label="车辆id" align="center" prop="vehicleId"></el-table-column>
      <el-table-column label="费用类型 0收入1支出" align="center" prop="costType"></el-table-column>
      <el-table-column label="费用名称" align="center" prop="costName"></el-table-column>
      <el-table-column label="发生时间" align="center" prop="buyTime" width="180"></el-table-column>
      <el-table-column label="费用说明" align="center" prop="remarks"></el-table-column>
      <el-table-column label="单位(元)" align="center" prop="amountStr"></el-table-column>
      <el-table-column label="图片列表 json list" align="center" prop="imageList"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['gwc:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['gwc:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改费用记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属作业公司" prop="companyId">
          <el-tree-select v-model="form.companyId" placeholder="请选择所属公司" clearable :data="treeList"
            :props="{ label: 'label' }" node-key="id" filterable />
        </el-form-item>
        <el-form-item label="驾驶员id" prop="driverId">
          <el-input v-model="form.driverId" placeholder="请输入驾驶员id" />
        </el-form-item>
        <el-form-item label="车辆id" prop="vehicleId">
          <el-input v-model="form.vehicleId" placeholder="请输入车辆id" />
        </el-form-item>
        <el-form-item label="费用类型 0收入1支出" prop="costType">
        </el-form-item>
        <el-form-item label="费用名称 0加油费1停车费2过路费3维修费4保养费5保险费6其他费用" prop="costName">
        </el-form-item>
        <el-form-item label="发生时间" prop="buyTime">
          <el-date-picker clearable v-model="form.buyTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择发生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用说明" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入费用说明" />
        </el-form-item>
        <el-form-item label="单位(元)" prop="amountStr">
          <el-input v-model="form.amountStr" placeholder="请输入单位分" />
        </el-form-item>
        <el-form-item label="图片列表 json list" prop="imageList">
          <el-input v-model="form.imageList" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record" lang="ts">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/gwc/record";
import { searchComponentType } from "@/components/tableRelate/searchTypeTs"
import { getSearchCompanyListRole } from "@/api/system/dept";
import useUserStore from '@/store/modules/user'
import searchType from "@/components/tableRelate/searchType.vue";
import dayjs from "dayjs"

const { proxy } = getCurrentInstance() as any;

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data: any = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    companyId: null,
    driverId: null,
    vehicleId: null,
    costType: null,
    costName: null,
    buyTime: null,
    remarks: null,
    amountStr: null,
    imageList: null,
  },
  rules: {
    companyId: [
      { required: true, message: "所属作业公司不能为空", trigger: "blur" }
    ],
  }
});

const sel_option = ref<any>({});
const treeList = ref([]);
const user = useUserStore().info as { userName: string, phonenumber: string, dept: { id: string, deptName: string } };
getSearchCompanyListRole().then(res => {
  treeList.value = res.data
  sel_option.value.companyId = res.data
});
const { queryParams, form, rules } = toRefs(data);

const navData = reactive([
  { label: "用车申请", value: "0,4,5" }, // 待审批 + 已驳回
  { label: "待送修", value: "0" }, // 已申请 
  { label: "待完成", value: "1" }, // 
  { label: "已完成", value: "2" },
])

const searchProps = reactive([
  { label: "车牌号", prop: "1", type: searchComponentType.input },
  { label: "所属部门", prop: "companyId", type: searchComponentType.treeSelect },
  { label: "委托维修单位", prop: "2", type: searchComponentType.input },
  { label: "送修人", prop: "3", type: searchComponentType.input },
])

/** 查询费用记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then((response: any) => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    companyId: null,
    driverId: null,
    vehicleId: null,
    costType: null,
    costName: null,
    buyTime: null,
    remarks: null,
    amountStr: null,
    imageList: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    createBy: null
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加费用记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getRecord(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改费用记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除费用记录编号为"' + _recordIds + '"的数据项？').then(function () {
    return delRecord(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

// /** 导出按钮操作 */
// function handleExport() {
//   proxy.download('gwc/record/export', {
//     ...queryParams.value
//   }, `费用记录_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
// }

getList();
</script>
